package com.atguigu.chapter02;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * Author: Pepsi
 * Date: 2023/7/24
 * Desc:  flink流处理的方式处理无界流数据（数据用socket端口模拟发送数据）
 */
public class Flink03_Streaming_unbounded_WordCount {
    public static void main(String[] args) throws Exception {

        // 拿到流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        // 读取端口里的数据
        DataStreamSource<String> dataStreamSource = env.socketTextStream("hadoop101", 9999);

        dataStreamSource
                .flatMap(new FlatMapFunction<String, String>() {
                    public void flatMap(String lineData, Collector<String> out) throws Exception {
                        String[] splits = lineData.split(" ");
                        for (String word : splits) {
                            out.collect(word);
                        }
                    }
                })
                .map(new MapFunction<String, Tuple2<String,Long>>() {
                    public Tuple2<String, Long> map(String word) throws Exception {
                        return Tuple2.of(word,1L);
                    }
                })
                .keyBy(new KeySelector<Tuple2<String, Long>, String>() {
                    public String getKey(Tuple2<String, Long> operationedTuple2) throws Exception {
                        return operationedTuple2.f0;
                    }
                })
                .sum(1)
                .print();

        env.execute();
    }
}
